package com.yq.testmodule.emoji

import android.annotation.SuppressLint
import android.content.Context
import android.text.Editable
import android.text.Spannable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ImageSpan
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputConnectionWrapper
import androidx.appcompat.widget.AppCompatEditText
import com.fmt.mvi.learn.gobal.log
import com.yq.testmodule.R
import net.lucode.hackware.magicindicator.buildins.UIUtil
import java.util.regex.Matcher
import java.util.regex.Pattern

class EmojiEditText @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatEditText(context, attrs) {




    init {
        addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            var flag = false //是否是重置后的情况

            override fun afterTextChanged(s: Editable?) {
                val originSelect = selectionStart
                if(flag){
                    flag = false
                    return
                }
                val emojiStr = dealEmojiStr(s.toString())
                flag = true
                setText(emojiStr)
                //还原选择的位置
                setSelection(originSelect)
            }

        })
    }

    override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
        return EmojiInputConnection(super.onCreateInputConnection(outAttrs), true)
    }



    @SuppressLint("UseCompatLoadingForDrawables")
    private fun dealEmojiStr(emojiStr: String): SpannableString {
        val newText = SpannableString(emojiStr)
        val pattern: Pattern = Pattern.compile("\\[.+?\\]")
        val matcher: Matcher = pattern.matcher(emojiStr)

        while (matcher.find()) {
            val group = matcher.group()
            if(EmojiDataManager.emojiMapDatas.containsKey(group)){
                val drawable = resources.getDrawable(EmojiDataManager.emojiMapDatas.get(group)!!)

                val dp15 = UIUtil.dip2px(context, 15.0)
                drawable.setBounds(0, 0, textSize.toInt(), textSize.toInt())
                val span = ImageSpan(drawable, ImageSpan.ALIGN_CENTER)
                newText.setSpan(
                    span,
                    matcher.start(),
                    matcher.end(),
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE
                )
            }

        }
        return newText
    }

    fun insertStr(first: String) {
        text?.insert(selectionStart,first)
    }


    inner class EmojiInputConnection(target: InputConnection?, mutable: Boolean) :
        InputConnectionWrapper(target, mutable) {

        //删除光标前后的长度
        override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
            //计算当前要删除的文字是否是
            "当前删除： $beforeLength - $afterLength".log()
            //获取当前最后一个满足表情的字符串起始位置
            val emojiStr = text.toString()
            val pattern: Pattern = Pattern.compile("\\[.+?\\]")
            val matcher: Matcher = pattern.matcher(emojiStr)
            val cursorPosition: Int = selectionStart
            // 查找匹配的表情符号
            while (matcher.find()) {
                val start: Int = matcher.start()
                val end: Int = matcher.end()
                "$start  $end  $cursorPosition".log()
                // 如果光标位置在表情符号范围内，删除表情符号
                if (cursorPosition in start..end) {
                    //
                    "ok".log()
                    return super.deleteSurroundingText(end - start, afterLength);
                }
            }

            return super.deleteSurroundingText(beforeLength, afterLength);
        }
    }
}